<template>
  <div class="page-container">
    <!-- 顶部标题栏 -->
    <header class="header">
      <BackBtn />
      <h1>用户列表</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <div class="search-row">
          <el-input v-model="searchText" placeholder="支持搜索姓名、手机号、所属单位、ID" class="search-input">
            <template #append>
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon>
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>

          <div class="date-range">
            <el-date-picker v-model="dateRange[0]" type="date" placeholder="开始日期" class="date-picker"
              @change="handleFilterChange" />
            <span class="separator">—</span>
            <el-date-picker v-model="dateRange[1]" type="date" placeholder="结束日期" class="date-picker"
              @change="handleFilterChange" />
          </div>

          <el-select v-model="sortType" placeholder="排序：注册时间(正序)" @change="handleFilterChange" class="sort-select">
            <el-option label="注册时间(正序)" value="asc" />
            <el-option label="注册时间(倒序)" value="desc" />
          </el-select>

          <el-select v-model="ethnicity" placeholder="民族筛选：全部" @change="handleFilterChange" class="filter-select">
            <el-option label="民族筛选：全部" value="all" />
            <el-option label="汉族" value="汉族" />
            <el-option label="蒙古族" value="蒙古族" />
            <el-option label="回族" value="回族" />
            <el-option label="藏族" value="藏族" />
            <el-option label="维吾尔族" value="维吾尔族" />
            <el-option label="苗族" value="苗族" />
            <el-option label="彝族" value="彝族" />
            <el-option label="壮族" value="壮族" />
            <el-option label="布依族" value="布依族" />
            <el-option label="朝鲜族" value="朝鲜族" />
            <el-option label="满族" value="满族" />
            <el-option label="侗族" value="侗族" />
            <el-option label="瑶族" value="瑶族" />
            <el-option label="白族" value="白族" />
            <el-option label="土家族" value="土家族" />
            <el-option label="哈尼族" value="哈尼族" />
            <el-option label="哈萨克族" value="哈萨克族" />
            <el-option label="傣族" value="傣族" />
            <el-option label="黎族" value="黎族" />
            <el-option label="傈僳族" value="傈僳族" />
            <el-option label="佤族" value="佤族" />
            <el-option label="畲族" value="畲族" />
            <el-option label="高山族" value="高山族" />
            <el-option label="拉祜族" value="拉祜族" />
            <el-option label="水族" value="水族" />
            <el-option label="东乡族" value="东乡族" />
            <el-option label="纳西族" value="纳西族" />
            <el-option label="景颇族" value="景颇族" />
            <el-option label="柯尔克孜族" value="柯尔克孜族" />
            <el-option label="土族" value="土族" />
            <el-option label="达斡尔族" value="达斡尔族" />
            <el-option label="仫佬族" value="仫佬族" />
            <el-option label="羌族" value="羌族" />
            <el-option label="布朗族" value="布朗族" />
            <el-option label="撒拉族" value="撒拉族" />
            <el-option label="毛南族" value="毛南族" />
            <el-option label="仡佬族" value="仡佬族" />
            <el-option label="锡伯族" value="锡伯族" />
            <el-option label="阿昌族" value="阿昌族" />
            <el-option label="普米族" value="普米族" />
            <el-option label="塔吉克族" value="塔吉克族" />
            <el-option label="怒族" value="怒族" />
            <el-option label="乌孜别克族" value="乌孜别克族" />
            <el-option label="俄罗斯族" value="俄罗斯族" />
            <el-option label="鄂温克族" value="鄂温克族" />
            <el-option label="德昂族" value="德昂族" />
            <el-option label="保安族" value="保安族" />
            <el-option label="裕固族" value="裕固族" />
            <el-option label="京族" value="京族" />
            <el-option label="塔塔尔族" value="塔塔尔族" />
            <el-option label="独龙族" value="独龙族" />
            <el-option label="鄂伦春族" value="鄂伦春族" />
            <el-option label="赫哲族" value="赫哲族" />
            <el-option label="门巴族" value="门巴族" />
            <el-option label="珞巴族" value="珞巴族" />
            <el-option label="基诺族" value="基诺族" />
          </el-select>

          <el-button :loading="exportLoading" class="export-btn" @click="handleExport">
            {{ exportLoading ? '导出中...' : '导 出' }}
          </el-button>
          <!-- <el-button type="primary" class="import-btn">批量导入</el-button> -->
        </div>

        <!-- 高级筛选 -->
        <div class="filter-row">
          <el-select v-model="identity" placeholder="身份筛选：全部" @change="handleFilterChange" class="filter-select">
            <el-option label="身份筛选：全部" value="all" />
            <el-option label="第十一届政协委员" value="第十一届政协委员" />
            <el-option label="第十届政协委员" value="第十届政协委员" />
            <el-option label="第九届政协委员" value="第九届政协委员" />
            <el-option label="联络员" value="联络员" />
            <el-option label="工作人员" value="工作人员" />
          </el-select>

          <el-select v-model="region" placeholder="地区筛选：全部" @change="handleFilterChange" class="filter-select">
            <el-option label="地区筛选：全部" value="all" />
            <el-option label="张家畔街道" value="张家畔街道" />
            <el-option label="东坑镇" value="东坑镇" />
            <el-option label="周河镇" value="周河镇" />
            <el-option label="天赐湾镇" value="天赐湾镇" />
            <el-option label="镇靖镇" value="镇靖镇" />
            <el-option label="海则滩镇" value="海则滩镇" />
            <el-option label="中山涧镇" value="中山涧镇" />
            <el-option label="龙洲镇" value="龙洲镇" />
            <el-option label="黄蒿界镇" value="黄蒿界镇" />
            <el-option label="红墩界镇" value="红墩界镇" />
            <el-option label="王渠则镇" value="王渠则镇" />
            <el-option label="杨米涧镇" value="杨米涧镇" />
            <el-option label="杨桥畔镇" value="杨桥畔镇" />
            <el-option label="席麻湾镇" value="席麻湾镇" />
            <el-option label="宁条梁镇" value="宁条梁镇" />
            <el-option label="高家堡镇" value="高家堡镇" />
            <el-option label="新桥镇" value="新桥镇" />
          </el-select>

          <el-select v-model="affiliation" placeholder="界别筛选：文化艺术界" @change="handleFilterChange" class="filter-select">
            <el-option label="界别筛选：全部" value="all" />
            <el-option label="中国共产党" value="中国共产党" />
            <el-option label="中国国民党革命委员会（民革）" value="中国国民党革命委员会（民革）" />
            <el-option label="中国民主同盟（民盟）" value="中国民主同盟（民盟）" />
            <el-option label="中国民主建国会（民建）" value="中国民主建国会（民建）" />
            <el-option label="中国民主促进会（民进）" value="中国民主促进会（民进）" />
            <el-option label="中国农工民主党" value="中国农工民主党" />
            <el-option label="中国致公党" value="中国致公党" />
            <el-option label="九三学社" value="九三学社" />
            <el-option label="台湾民主自治同盟（台盟）" value="台湾民主自治同盟（台盟）" />
            <el-option label="无党派人士" value="无党派人士" />
            <el-option label="中国共产主义青年团" value="中国共产主义青年团" />
            <el-option label="中华全国总工会" value="中华全国总工会" />
            <el-option label="中华全国妇女联合会" value="中华全国妇女联合会" />
            <el-option label="中华全国青年联合会" value="中华全国青年联合会" />
            <el-option label="中华全国工商业联合会" value="中华全国工商业联合会" />
            <el-option label="科学技术界" value="科学技术界" />
            <el-option label="社会科学界" value="社会科学界" />
            <el-option label="经济界" value="经济界" />
            <el-option label="农业界" value="农业界" />
            <el-option label="教育界" value="教育界" />
            <el-option label="体育界" value="体育界" />
            <el-option label="新闻出版界" value="新闻出版界" />
            <el-option label="医药卫生界" value="医药卫生界" />
            <el-option label="对外友好界" value="对外友好界" />
            <el-option label="社会福利和社会保障界" value="社会福利和社会保障界" />
            <el-option label="文化艺术界" value="文化艺术界" />
            <el-option label="科学技术协会" value="科学技术协会" />
            <el-option label="少数民族界" value="少数民族界" />
            <el-option label="宗教界" value="宗教界" />
            <el-option label="台湾同胞联谊会" value="台湾同胞联谊会" />
            <el-option label="港澳同胞（香港、澳门代表）" value="港澳同胞（香港、澳门代表）" />
            <el-option label="特邀香港人士" value="特邀香港人士" />
            <el-option label="特邀澳门人士" value="特邀澳门人士" />
            <el-option label="特别邀请人士" value="特别邀请人士" />
            <el-option label="环境资源界" value="环境资源界" />
          </el-select>

          <el-select v-model="gender" placeholder="性别筛选：全部" @change="handleFilterChange" class="filter-select"
            style="margin-left: -10px;">
            <el-option label="性别筛选：全部" value="all" />
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <div class="news-list" v-loading="loading" element-loading-text="加载中..."
          :element-loading-background="'rgba(0, 0, 0, 0)'">
          <!-- 表头 -->
          <div class="news-header">
            <div class="header-item">姓名</div>
            <div class="header-item">身份</div>
            <div class="header-item">地区</div>
            <div class="header-item">界别</div>
            <div class="header-item"></div>
            <div class="header-item">
              <el-button type="danger" size="small" @click="handleSaveScores">保存打分</el-button>
              <el-button type="danger" size="small" @click="handleClearScores">全部清零</el-button>
            </div>
          </div>

          <!-- 数据列表 -->
          <div v-if="!loading && users.length === 0" class="empty-data">
            <el-empty description="暂无数据" />
          </div>
          <div v-else v-for="(item, index) in users" :key="index" class="news-item">
            <div class="line"></div>
            <div class="news-info" @mouseenter="handleMouseEnter(item, $event)" @mousemove="handleMouseMove"
              @mouseleave="handleMouseLeave" style="cursor: pointer;">
              <div class="info-value">{{ item.uname }}</div>
              <div class="info-value">{{ item.identity }}</div>
              <div class="info-value">{{ item.region }}</div>
              <div class="info-value">{{ item.affiliation }}</div>
              <div class="info-value">
                <el-input-number 
                  v-model="item.score" 
                  :min="0" 
                  :max="100" 
                  :precision="1"
                  :step="0.1"
                  @click.stop
                  @change="handleScoreChange($event, item)"
                  size="small"
                  :controls="false"
                  style="width: 80px;height:28px;margin-left: 50px;"
                />
              </div>
              <div class="news-actions">
                <template v-if="item.status === '已注销'">
                  <el-button type="info" disabled>已注销</el-button>
                </template>
                <template v-else>
                  <el-button type="danger" @click.stop="handleCancel(item)">注销</el-button>
                </template>
                <el-button type="primary" @click.stop="handleEdit(item)">详情</el-button>
              </div>
            </div>
          </div>

          <!-- 用户详情浮窗 -->
          <div v-if="showUserDetail" class="user-detail-popup" :style="popupStyle">
            <div class="popup-content">
              <div class="detail-item">
                <span class="label">性别：</span>
                <span class="value">{{ currentUserDetail.gender }}</span>
              </div>
              <div class="detail-item">
                <span class="label">民族：</span>
                <span class="value">{{ currentUserDetail.ethnicity }}</span>
              </div>
              <div class="detail-item">
                <span class="label">出生日期：</span>
                <span class="value">{{ currentUserDetail.birthDate }}</span>
              </div>
              <div class="detail-item">
                <span class="label">手机号：</span>
                <span class="value">{{ currentUserDetail.phone }}</span>
              </div>
              <div class="detail-item">
                <span class="label">所属单位：</span>
                <span class="value">{{ currentUserDetail.unit }}</span>
              </div>
              <div class="detail-item">
                <span class="label">注册时间：</span>
                <span class="value">{{ currentUserDetail.registrationTime }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            :background="false" layout="prev, pager, next, jumper" :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUsersStore } from '@/stores/users'
import { storeToRefs } from 'pinia'
import { getAllUsers, getUserDetail, updateUserStatus, exportUsers, updateUserScore, clearAllScores } from '@/api/admin'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'

const router = useRouter()

// 状态定义
const searchText = ref('')
const dateRange = ref([])
const sortType = ref('asc')
const identity = ref('all')
const region = ref('all')
const affiliation = ref('all')
const ethnicity = ref('all')
const gender = ref('all')
const users = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const onlyApproved = ref(true)
const exportLoading = ref(false)

// 重置所有筛选条件的函数
const resetFilters = () => {
  searchText.value = ''  // 重置搜索文本
  dateRange.value = []  // 重置日期范围
  sortType.value = 'asc'  // 重置排序为默认的正序
  identity.value = 'all'  // 重置身份筛选为全部
  region.value = 'all'  // 重置地区筛选为全部
  affiliation.value = 'all'  // 重置界别筛选为全部
  ethnicity.value = 'all'  // 重置民族筛选为全部
  gender.value = 'all'  // 重置性别筛选为全部
  pageNum.value = 1  // 重置页码
}

// 在组件挂载时获取用户数据
onMounted(() => {
  resetFilters()
  fetchUsers()
})

// 添加组件卸载钩子
onUnmounted(() => {
  resetFilters()  // 组件卸载时重置所有筛选条件
})

// 获取用户数据
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      searchText: searchText.value,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      sortType: sortType.value,
      identity: identity.value,
      region: region.value,
      affiliation: affiliation.value,
      ethnicity: ethnicity.value,
      gender: gender.value,
      onlyApproved: onlyApproved.value
    }

    const res = await getAllUsers(params)
    if (res.code === 200) {
      users.value = res.data.items
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pageNum.value = 1
  fetchUsers()
}

// 处理筛选条件变化
const handleFilterChange = () => {
  pageNum.value = 1
  fetchUsers()
}

// 分页大小改变
const onSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

// 页码改变
const onCurrentChange = (val) => {
  pageNum.value = val
  fetchUsers()
}

// 处理注销
const handleCancel = async (item) => {
  try {
    await ElMessageBox.confirm(`确定要注销 ${item.uname} 的账号吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await updateUserStatus(item.uid, '已注销')

    if (response.code === 200) {
      ElMessage.success('已注销用户')
      // 直接更新本地数据状态，避免重新请求
      item.status = '已注销'
      // 刷新整个列表
      fetchUsers()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('注销失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 查看用户详情\修改
const handleEdit = (item) => {
  router.push({
    name: 'UserEdit',
    query: { uid: item.uid }
  })
}

// 用户详情浮窗相关逻辑
const showUserDetail = ref(false)
const currentUserDetail = ref({})
const popupStyle = ref({
  position: 'fixed',
  top: '0px',
  left: '0px'
})

// 处理鼠标进入
const handleMouseEnter = async (item, event) => {
  try {
    const res = await getUserDetail(item.uid)
    if (res.code === 200) {
      currentUserDetail.value = res.data
      updatePopupPosition(event)
      showUserDetail.value = true
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
  }
}

// 处理鼠标移动
const updatePopupPosition = (event) => {
  const mouseX = event.clientX
  const mouseY = event.clientY
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight

  const popupWidth = 300
  const popupHeight = 350

  let left = mouseX + 15
  let top = mouseY + 15

  if (left + popupWidth > windowWidth) {
    left = mouseX - popupWidth - 15
  }

  if (top + popupHeight > windowHeight) {
    top = mouseY - popupHeight - 15
  }

  popupStyle.value = {
    position: 'fixed',
    top: `${top}px`,
    left: `${left}px`,
  }
}

// 处理鼠标移动
const handleMouseMove = (event) => {
  if (showUserDetail.value) {
    updatePopupPosition(event)
  }
}

// 处理鼠标离开
const handleMouseLeave = () => {
  showUserDetail.value = false
}

// 导出列表
const handleExport = async () => {
  if (exportLoading.value) return
  exportLoading.value = true
  try {
    // 先保存所有分数
    const updatePromises = users.value
      .filter(user => user.score !== undefined)
      .map(user => updateUserScore(user.uid, user.score));

    // 等待所有分数更新完成
    await Promise.all(updatePromises);

    // 添加参数检查日志
    console.log('导出参数:', {
      searchText: searchText.value,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
      sortType: sortType.value,
      identity: identity.value,
      region: region.value,
      affiliation: affiliation.value,
      ethnicity: ethnicity.value,
      gender: gender.value,
      onlyApproved: true, // 用户列表页面只导出已通过的用户
    });

    const response = await exportUsers(
      searchText.value,
      dateRange.value[0],
      dateRange.value[1],
      sortType.value,
      '',
      identity.value === 'all' ? '' : identity.value,
      region.value === 'all' ? '' : region.value,
      affiliation.value === 'all' ? '' : affiliation.value,
      ethnicity.value === 'all' ? '' : ethnicity.value,
      gender.value === 'all' ? '' : gender.value,
      true
    );

    // 调试信息
    console.log('Response headers:', response.headers);
    console.log('Response type:', response.type);
    console.log('Response size:', response.size);

    // 检查响应是否为空
    if (!response || response.size === 0) {
      throw new Error('导出的文件为空');
    }

    // 检查响应类型
    const contentType = response.type;
    if (!contentType.includes('spreadsheetml.sheet')) {
      // 如果响应不是Excel文件，尝试读取错误信息
      const text = await response.text();
      throw new Error(text || '导出的文件格式不正确');
    }

    // 创建下载链接
    const blob = new Blob([response], { type: contentType });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = `用户列表_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(link);
    link.click();

    // 清理资源
    window.URL.revokeObjectURL(downloadUrl);
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('Export error:', error);
    ElMessage.error(error.message || '导出失败');
  } finally {
    exportLoading.value = false
  }
}

const handleSaveScores = async () => {
  try {
    // 创建一个保存所有更新操作的Promise数组
    const updatePromises = users.value
      .filter(user => user.score !== undefined) // 只处理有分数的用户
      .map(user => updateUserScore(user.uid, user.score));

    // 等待所有更新操作完成
    await Promise.all(updatePromises);
    
    ElMessage.success('保存成功！');
  } catch (error) {
    console.error('保存分数失败:', error);
    ElMessage.error('保存失败');
  }
}

const handleClearScores = () => {
  ElMessageBox.confirm('是否确认全部清零？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await clearAllScores();
      // 更新本地数据
      users.value.forEach(user => {
        user.score = 0;
      });
      ElMessage.success('已清零所有分数');
    } catch (error) {
      console.error('清零失败:', error);
      ElMessage.error('清零失败');
    }
  }).catch(() => {
    // 用户点击取消，不做任何操作
  });
}

const handleScoreChange = (value, item) => {
  if (value === null || value === '') {
    item.score = 0;
    return;
  }
  
  // 转换为数字并限制小数位数
  let score = Number(value);
  
  // 检查是否为有效数字
  if (isNaN(score)) {
    item.score = 0;
    ElMessage.warning('请输入有效的数字');
    return;
  }
  
  // 限制范围在0-100之间
  if (score < 0) {
    score = 0;
    ElMessage.warning('分数不能小于0');
  } else if (score > 100) {
    score = 100;
    ElMessage.warning('分数不能大于100');
  }
  
  // 限制小数位数为1位
  score = Number(score.toFixed(1));
  
  // 更新分数
  item.score = score;
}
</script>

<style scoped>
@import '@/assets/css/header/index.css';
@import '@/assets/css/user/audit.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/select.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';

.search-section {
  /* background: white; */
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 10px;
  /* box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); */
  margin-left: 105px;
  min-width: 900px;
  width: 84%;
}

/* 搜索框特定样式 */
.search-input {
  margin-bottom: 20px;
}

.search-input :deep(.el-input__wrapper) {
  height: 40px !important;
  border-radius: 8px 0 0 8px !important;
  padding: 0 12px !important;
  box-sizing: border-box;
}

.search-input :deep(.el-input:hover .el-input__wrapper) {
  box-shadow: 0 0 0 1px #c62828 inset !important;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #c62828 inset !important;
}

.search-input :deep(.el-input-group__append) {
  padding: 0 !important;
  border: none !important;
  background: none !important;
}

/* 搜索按钮样式 */
.search-btn {
  background-color: #c62828 !important;
  border: none;
  height: 40px;
  width: 180px;
  color: white;
  padding: 5px 10px;
  border-radius: 0 8px 8px 0 !important;
  cursor: pointer;
}

.search-btn:hover {
  background-color: #a91919 !important;
}

.search-btn .el-icon {
  font-size: 20px;
  color: white;
}

/* 添加新的样式 */
.el-input-number {
  width: 80px;
}

.header-item .el-button {
  margin: 0 5px;
}

.news-header .header-item:last-child {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

/* 添加表格内容超出省略的样式 */
.info-value {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 设置最大宽度 */
  padding: 0 10px;
}


/* 调整按钮样式，使其与注销按钮一致 */
.header-item .el-button {
  margin: 0 10px;
  height: 30px;
  font-size: 14px;
}

.header-item .el-button:hover {
  background-color: #a91919;
  border-color: #a91919;
}

.header-item {
  padding: 0 45px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>